using System;
using System.Threading;
using System.Threading.Tasks;
using muduoDotNet;

class DebugTest
{
    static void Main(string[] args)
    {
        Logger.Info("=== EventLoop Debug Test ===");
        
        try
        {
            SimpleEventLoopTest();
            Logger.Info("✅ Simple EventLoop test passed!");
        }
        catch (Exception ex)
        {
            Logger.Error($"❌ Test failed: {ex}");
        }
        
        Console.ReadKey();
    }
    
    static void SimpleEventLoopTest()
    {
        var loop = new EventLoop();
        bool taskExecuted = false;
        var resetEvent = new ManualResetEventSlim(false);
        
        Logger.Info("Creating EventLoop");
        
        // 启动事件循环
        var loopTask = Task.Run(() =>
        {
            Logger.Info("Starting EventLoop...");
            try
            {
                loop.Start();
                Logger.Info("EventLoop started");
            }
            catch (Exception ex)
            {
                Logger.Error($"EventLoop exception: {ex}");
                throw;
            }
        });
        
        // 等待事件循环启动
        Thread.Sleep(200);
        Logger.Info("EventLoop should be running now");
        
        // 添加任务
        Logger.Info("Queueing task...");
        loop.QueueInLoop(() =>
        {
            Logger.Info("Task executing!");
            taskExecuted = true;
            resetEvent.Set();
        });
        
        // 等待任务执行
        Logger.Info("Waiting for task completion...");
        bool completed = resetEvent.Wait(3000);
        
        Logger.Info($"Task completed: {completed}, taskExecuted: {taskExecuted}");
        
        // 停止事件循环
        Logger.Info("Stopping EventLoop...");
        loop.Stop();
        
        // 等待线程结束
        loopTask.Wait(2000);
        
        Logger.Info("EventLoop stopped");
        
        if (!completed || !taskExecuted)
            throw new Exception("Task was not executed properly");
        
        loop.Dispose();
        Logger.Info("Test completed successfully");
    }
}